﻿package shooter
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import render3d.interfaces.IRender3DAdapter;

	/**
	 * Bullet shoot, flying, killing a monster
	 * @author Exey Panteleev
	 */
	
	public class BulletsController
	{
		private const BULLET_RADIUS:uint = 64;
		private const BULLET_SPEED:uint = 100;
		private const MAX_BULLET_DISTANCE:uint = 4000;
		
		private var bullets:Array = new Array();
		
		private var game:Game;
		private var render:IRender3DAdapter; 
		
		public function BulletsController(game:Game)
		{
			this.game = game;
			this.render = game.render;
		}

		public function shoot():void
		{
			var bullet:Bullet = new Bullet( render, BULLET_RADIUS );
			bullet.setTransform(render.getCameraTransformation());
			bullet.appendTranslation(0, 0, -32)
			bullet.moveBackward(75);
			bullets.push(bullet);
			render.addChild(bullet);
		}
		
		public function update( monsters:Object ):void
		{
			// move bullets forward and check for collisions with monsters
			for each(var bullet:Bullet in bullets) {
				// moving bullets
				bullet.moveForward( BULLET_SPEED );
				// check for collision bullet with monsters
				for (var monsterId:String in monsters) {
					var isCollide:Boolean = bullet.hitTestObject2(monsters[monsterId], 48)
					if (isCollide) { 						
						var monster:Monster = monsters[monsterId]
						if (!monster.isAlive) continue;
						delete monsters[monsterId];
						monster.animateOut();
						game.addScore();
					}
				}
				// destroy bullet if it's out off the max distance
				if (Math.abs(bullet.getPosition().x) > MAX_BULLET_DISTANCE || Math.abs(bullet.getPosition().y) > MAX_BULLET_DISTANCE || Math.abs(bullet.getPosition().z) > MAX_BULLET_DISTANCE) {
					bullet.destroy();
					bullets.splice(bullets.indexOf(bullet), 1 );
				}
			}
		}
		
	}
}